package com.ysd.lis.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysd.common.Result;
import com.ysd.common.dto.ColumnAndCommentDto;
import com.ysd.common.dto.ColumnValueDto;
import com.ysd.lis.entity.PubTaskColumnConnect;
import com.ysd.lis.entity.PubTaskTemplet;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.mapper.PublicTaskMapper;
import com.ysd.lis.request.DynamicTablePageData;
import com.ysd.lis.request.TransmitTodoParam;
import com.ysd.lis.service.PublicTaskService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.UniqueIdGenerator;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: server_lis
 * @author: liuQi
 * @create: 2023-11-14 15:21
 */
@Service
public class PublicTaskServiceImpl implements PublicTaskService {
    @Resource
    private PublicTaskMapper publicTaskMapper;

    @Resource
    private PubTaskTempletServiceImpl pubTaskTempletService;

    @Override
    public Result findTableNames() {
        List<Map<String, String>> tableNames = publicTaskMapper.findTableNames("TRANSMIT_");
        return Result.succ(1, "查询成功！", tableNames);
    }

    @Override
    public Result findColumnsByTableName(String tableName) {
        List<ColumnAndCommentDto> ColumnAndComments = publicTaskMapper.findColumnsByTableName(tableName);
        String[] arrs = {"TITLE", "CONTENT"};
        List<ColumnAndCommentDto> collect = ColumnAndComments.stream().filter(item -> Arrays.asList(arrs).contains(item.getColumnName())).collect(Collectors.toList());
        return Result.succ(1, "查询成功！", collect);
    }

    //ColumnAndCommentDto(columnName=FEE_NAME, comments=收费项目名称 一般是大项名称，肝功，肾功，血糖，生化全项, dataType=varchar, columnId=4)
    @Override
    public Result findColumnsByTableNameToCamel(String tableName) {
        List<ColumnAndCommentDto> ColumnAndComments = publicTaskMapper.findColumnsByTableName(tableName);
        List<Map> returnList = new ArrayList<>();
        for (ColumnAndCommentDto columnAndComment : ColumnAndComments) {
            Map map = new HashMap();
            map.put("code", StrUtil.toCamelCase(columnAndComment.getColumnName().toLowerCase()));
            map.put("common", columnAndComment.getComments());
            if (columnAndComment.getDataType().endsWith("varchar")) {
                map.put("coloumType", 1);
            } else if (columnAndComment.getDataType().startsWith("datetime")) {
                map.put("coloumType", 3);
            } else {
                map.put("coloumType", 2);
            }
            map.put("type", 2);
            returnList.add(map);
        }
        return Result.succ(1, "查询成功！", returnList);
    }

    @Override
    public Result getColumnsByTableName(String tableName) {
        List<ColumnAndCommentDto> ColumnAndComments = publicTaskMapper.findColumnsByTableName(tableName);
        String[] arrs = {"TITLE", "USER_NAME", "TODO_TIME", "MODULE_NAME", "ASSIGN_NAME", "START_TIME", "FINISH_TIME", "CONTENT"};
        List<ColumnAndCommentDto> collect = ColumnAndComments.stream().filter(item -> Arrays.asList(arrs).contains(item.getColumnName())).collect(Collectors.toList());
        return Result.succ(1, "查询成功！", collect);
    }

    @Override
    public Result insertTransmitTodoData(TransmitTodoParam transmitTodoParam) {
        List<ColumnValueDto> list = builderAddBaseColumn();
        if (transmitTodoParam.getList().size() > 0) {
            list.addAll(transmitTodoParam.getList());
        }
        int i = publicTaskMapper.insertTransmitTodoTable(transmitTodoParam.getTableName(), list);
        return Result.succ(1, "添加成功！", null);
    }

    @Override
    public Result updateTransmitTodoTable(TransmitTodoParam transmitTodoParam) {
        List<ColumnValueDto> list = builderEditBaseColumn();
        if (transmitTodoParam.getList().size() > 0) {
            list.addAll(transmitTodoParam.getList());
        }
        int i = publicTaskMapper.updateTransmitTodoTable(transmitTodoParam.getTableName(), list);
        return Result.succ(1, "编辑成功！", i);
    }

    /**
     * 具体业务插入数据公共方法
     *
     * @param params
     * @return
     */
    @Override
    public Result pageInfoAddTransmitTodoTable(Map<String, Object> params) {
        // 1、通过页面编码查询模版列表，获取所有的模版列表
        List<PubTaskTemplet> pubTaskTemplets = pubTaskTempletService.findTaskTempleListByPageCode(params.get("pageCode").toString(), params.containsKey("code") ? params.get("code").toString() : null);
        int i = 0;
        for (PubTaskTemplet pubTaskTemple : pubTaskTemplets) {
            List<PubTaskColumnConnect> targetTableColumnData = pubTaskTemple.getTargetTableColumnData();
            List<ColumnValueDto> columnValueDtos = buildColumnValueDtos(targetTableColumnData, params);
            i = publicTaskMapper.insertTransmitTodoTable(pubTaskTemple.getTargetTable(), columnValueDtos);
        }
        if (i > 0) {
            return Result.succ(1, "任务添加成功 ！", i);
        } else {
            return Result.fail("添加失败！");
        }
    }

    /**
     * 动态查询数据
     *
     * @param tableName
     * @return
     */
    @Override
    public Result getDynamicTableData(String tableName) {
        List<String> columnList = getColumnList();
        List<Map<String, Object>> transmitTodoData = getTransmitTodoData(tableName, columnList);
        return Result.succ(1, "查询成功！", transmitTodoData);
    }

    @Override
    public Result getDynamicTablePageData(DynamicTablePageData dynamicTablePageData) {
        List<String> columnList = getColumnList();
        Page<Map<String, Object>> transmitTodoPageData = getTransmitTodoPageData(dynamicTablePageData.getTableName(), columnList, dynamicTablePageData.getPageIndex(), dynamicTablePageData.getPageSize());
        return Result.succ(1, "查询成功！", transmitTodoPageData);
    }

    /**
     * 动态删除数据
     *
     * @param id
     * @param tableName
     * @return
     */
    @Override
    public Result deleteDynamicTableData(String id, String tableName) {
        boolean b = publicTaskMapper.deleteDynamicTableData(tableName, id);
        if (b) {
            return Result.succ(1, "删除成功！", null);
        } else {
            return Result.fail("删除失败！");
        }
    }

    public List<Map<String, Object>> getTransmitTodoData(String tableName, List<String> columnList) {
        List<Map<String, Object>> transmitTodoData = publicTaskMapper.getTransmitTodoData(tableName, columnList);
        return transmitTodoData;
    }

    public Page<Map<String, Object>> getTransmitTodoPageData(String tableName, List<String> columnList, Integer pageIndex, Integer pageSize) {
        Page<Map<String, Object>> page = new Page();
        Integer startSet;
        Integer endSet;
        if ((pageIndex - 1) <= 0) {
            startSet = 0;
            endSet = startSet + pageSize;
        } else {
            startSet = (pageIndex - 1) * pageSize + 1;
            endSet = startSet + pageSize - 1;
        }
        page.setTotal(publicTaskMapper.getDataCount(tableName));
        page.setRecords(publicTaskMapper.getPageData(tableName, columnList, startSet, endSet));
        return page;
    }

    public List<ColumnValueDto> buildColumnValueDtos(List<PubTaskColumnConnect> targetTableColumnData, Map<String, Object> map) {
        List<ColumnValueDto> list = builderAddBaseColumn();
        List<ColumnValueDto> collect = targetTableColumnData.stream().filter(item -> StringUtils.isNotBlank(item.getPageColumn())).map(item -> {
            String value = StrUtil.format(item.getPageColumn(), map);
            return new ColumnValueDto(item.getColumnName(), value, item.getDataType());
        }).collect(Collectors.toList());
        list.addAll(collect);
        if (map.containsKey("templetId")) {
            list.add(new ColumnValueDto("TEMPLET_ID", map.get("templetId").toString(), "NVARCHAR2"));
        }
        return list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(ColumnValueDto::getColumn))), ArrayList::new));
    }

    /**
     * 构建添加默认插入字段
     *
     * @return
     */
    public List<ColumnValueDto> builderAddBaseColumn() {
        SysUser user = RedisUserManager.getUser();
        Assert.notNull(user, "SysUser cannot be empty");
        List<ColumnValueDto> list = new ArrayList<>();
        list.add(new ColumnValueDto("ID", IdUtil.getSnowflake().nextId() + "", "NVARCHAR2"));
        list.add(new ColumnValueDto("ORG_ID", user.getOrgId(), "NVARCHAR2"));
        list.add(new ColumnValueDto("DEPT_ID", user.getDeptId(), "NVARCHAR2"));
        list.add(new ColumnValueDto("USER_ID", user.getId(), "NVARCHAR2"));
        list.add(new ColumnValueDto("USER_NAME", user.getUsername(), "NVARCHAR2"));
        list.add(new ColumnValueDto("CREATOR", user.getUsername(), "NVARCHAR2"));
        list.add(new ColumnValueDto("EDITOR", user.getUsername(), "NVARCHAR2"));
        list.add(new ColumnValueDto("START_TIME", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "DATE"));
        list.add(new ColumnValueDto("TODO_TIME", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "DATE"));
        list.add(new ColumnValueDto("CREATE_TIME", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "DATE"));
        list.add(new ColumnValueDto("EDIT_TIME", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "DATE"));
        list.add(new ColumnValueDto("DEL_FLAG", "0", "NVARCHAR2"));
        return list;
    }

    public List<ColumnValueDto> builderEditBaseColumn() {
        SysUser user = RedisUserManager.getUser();
        List<ColumnValueDto> list = new ArrayList<>();
        list.add(new ColumnValueDto("ID", "271769943236608", "NVARCHAR2"));
        list.add(new ColumnValueDto("EDITOR", user.getUsername(), "NVARCHAR2"));
        list.add(new ColumnValueDto("EDIT_TIME", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "DATE"));
        list.add(new ColumnValueDto("DEL_FLAG", "0", "NVARCHAR2"));
        return list;
    }

    public List<String> getColumnList() {
        List<String> columnList = new ArrayList<>();
        columnList.add("ID");
        columnList.add("ORG_ID");
        columnList.add("USER_NAME");
        columnList.add("MODULE_NAME");
        columnList.add("CONTENT");
        columnList.add("TITLE");
        columnList.add("START_TIME");
        columnList.add("TODO_TIME");
        columnList.add("TEMPLET_ID");
        return columnList;
    }
}
